using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


namespace CoreLibrary
{
    public class EntityUtil
    {
        /// <summary>
        /// 利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制  
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="realObject">复制对象</param>
        /// <returns></returns>
        public static T Clone<T>(T realObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, realObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }

        /// <summary>
        /// 复制Entity中的值
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="sourceEntity">源Entity</param>
        /// <param name="targetEntity">目标Entity</param>
        public static void WrapperEntity<T>(T sourceEntity, T targetEntity)
        {
            Type paramType = typeof(T);
            PropertyInfo[] pInfo = paramType.GetProperties();
            foreach (PropertyInfo pi in pInfo)
            {
                paramType.GetProperty(pi.Name).SetValue(targetEntity, paramType.GetProperty(pi.Name).GetValue(sourceEntity, null), null);
            }
        }
    }
}
